<?php
header('Content-type:text/html; charset=utf-8');

    //echo 'test web page<br>';
    //echo 'user = '.$_GET['var1'].'<br>';
    $user = $_GET['var1'];
    //echo 'collection = '.$_GET['var2'].'<br>';
    $collection = $_GET['var2'];    
    //echo 'board = '.$_GET['var3'].'<br>';
    $board = $_GET['var3'];
    function authenticate()
    {
        header('WWW-Authenticate: Basic realm="Basic authentication"');
        header('HTTP/1.1 401 Authorization Required');
        echo "Для доступа к ресурсу требуется ввести правильное имя и пароль\n";
        exit;
    }

    if (!isset($_SERVER['PHP_AUTH_USER']) ||
        ($user != $_SERVER['PHP_AUTH_USER'])) {
        authenticate();
    }

if ($_SERVER['REQUEST_METHOD'] != 'GET')
{
    header("HTTP/1.1 404  Not supported");
    echo "Not supported";
    return;
}

//Fall trhough, it IS a GET,  and a valid board... display web page
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>


    <title><?php echo $board ?> location</title><link rel="shortcut icon" href="favicon.ico" />
    <link href="Javascript/mchp.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://www.ajax-cross-domain.com/cgi-bin/ACD/ACD.js?uri=(http://linux.mchpcloud.com)"></script>
        <script src="Javascript/mchp.js" type="text/javascript"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    </head>
    <body>
        <div id="shadow-one">
            <div id="shadow-two">
                <div id="shadow-three">
                    <div id="shadow-four">
                        <div id="page">
                            <div style="padding: 0pt 0pt 5px 5px;"><img src="./Javascript/mchp.gif" alt="Microchip" /></div>
                            <div id="title">
                                <?php
                                    echo '<div class="right">TCP/IP Облачный демо-сервер</div>';
                                ?>
                                <span id="hello">&nbsp;</span>
                            </div>
                            <br />
                            <div style="margin-left: 0px; width: 635px;" id="content">
                                <div style="margin-left: 0px; width: 645px;" id="status">
                                    <div id="loading" style="display: none;">Ошибка:<br />
                                        Демо-плата не обновлена</div>
                                    <div id="display"> <span style="float: right; font-size: 9px; font-weight: normal; padding-top: 8px; text-indent: 0px;"></span>
                                        <p style="margin-left: 0px; width: 669px;"></p>
                                        <table style="text-align: left; width: 609px; height: 56px;" border="0" cellpadding="2" cellspacing="2">
                                            <tbody>
                                                <tr>
                                                    <td style="width: 284px;">
                                                        <div style="text-align: center;">Светодиоды: <br /><small><small style="font-weight: normal;"><small>(Кликните чтобы изменить)</small></small></small>
                                                            <span class="leds">
                                                                <a id="led2" onclick="toggleLED(4);">&#8226;</a>
                                                                <a id="led1" onclick="toggleLED(2);">&#8226;</a>
                                                                <a id="led0">&#8226;</a>
                                                            </span>
                                                        </div>
                                                        <span class="leds"> </span></td>
                                                    <td style="width: 305px; text-align: center;">Кнопка:<br />
                                                       <span id="btn0">?</span></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                        <table style="width: 100%; text-align: left; margin-left: auto; margin-right: auto;" border="0" cellpadding="2" cellspacing="2">
                                            <tbody>
                                                <tr>
                                                    <td>
                                                        <p style="text-align: center;">Дополнительная информация: <span id="pot0" style="font-weight: normal;">?</span></p>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                        <br />
                                        <table style="text-align: left; width: 609px; height: 87px;" border="0" cellpadding="2" cellspacing="2">
                                            <tbody>
                                                <tr>
                                                    <td><div style="text-align: center;">Контролируемое устройство:<br />
                                                            <div id="thisdevice">
                                                            <?php
                                                            echo $user."/".$collection."/".$board."<br>
                                                                ";
                                                            ?>
                                                            </div>
                                                            <input name="Connect" id="Dis_Connect" value=" Подключить " onclick="Connect_disconnect()" type="button" style="color:#1C6EA9;width:100px;height:30px"/><br /></div>
                                                        <br /></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                        <br />
                                    </div>
                                    <div>
                                        </br><span><button onclick="home()" style="color:#1C6EA9;width:150px;height:20px">Переход к коллекции</button></span>
                                        </br><span><button id="delboard" onclick="delboard()" style="color:#ff0000;width:150px;height:20px">Удалить устройство</button></span>
                                        <span style="float: right; font-size: 9px; font-weight: normal; padding-top: 8px; text-indent: 0px;" id="TableResponse">Ответ:</span>
                                    </div>
                                </div>
                                <div><br />
                                </div>
                            </div>

                            


                            <script type="text/javascript">
                                var URL = "";
                                //var URL = "http://54.218.57.68";
                                //var URL = "http://54.218.30.227";
                                
                                var user = <?php echo '"'.$user.'"'?>;
                                var collection = <?php echo '"'.$collection.'"'?>;
                                var boardname = <?php echo '"'.$board.'"'?>;
                                
                                setTimeout("validateboard()", 250);
                                var gotResponse = 0;
                                function validateboard()
                                {
                                    newAJAXCommand(URL+'/xml/' + user + '/' + collection + '/' + boardname + '/', "GET" ,validateboardresponse);
                                    setTimeout("did_we_get_response()",1000)
                                }
                                function validateboardresponse(xmlData)
                                {
                                    if(getXMLValue(xmlData, 'error') != null)
                                    {
                                        document.getElementById('thisdevice').innerHTML = getXMLValue(xmlData, 'error');
                                        document.getElementById("Dis_Connect").disabled=true;
                                        document.getElementById("delboard").disabled=true;

                                    }
                                    gotResponse = 1;
                                }
                                function did_we_get_response()
                                {
                                    if (!gotResponse)
                                    {
                                        document.getElementById('thisdevice').innerHTML = "Unable to communicate with server";
                                        document.getElementById("Dis_Connect").disabled=true;
                                        document.getElementById("delboard").disabled=true
                                    }
                                }

                                function delboard()
                                {
                                    var r = confirm("Уверены ?");
                                        if (r == false)
                                        {
                                            return;
                                        };
                                    newAJAXCommand(URL+'/xml/' + user + '/' + collection + '/' + boardname + '/',"DELETE",refresh,0);
                                }
                                function refresh()
                                {
                                    window.location = "../";//refresh page
                                }
                                function home()
                                {
                                    window.location = "../..";
                                }
                                // Parses the xmlResponse from status.xml and updates the status box
                                var Time = new Date();
                                var AlreadyCalled = 0;
                                setTimeout("DisplayTime()", 250);
                                
                                function DisplayTime()
                                {
                                    var d = new Date();
                                    setTimeout("DisplayTime()", 250);
                                    var month = d.getMonth() + 1
                                    var day = d.getDate()
                                    var year = d.getFullYear()
                                    var hours = d.getHours()
                                    var minutes = d.getMinutes()
                                    var seconds = d.getSeconds()
                                    if (hours < 10) {
                                        hours = "0" + hours
                                    }
                                    if (minutes < 10) {
                                        minutes = "0" + minutes
                                    }
                                    if (seconds < 10) {
                                        seconds = "0" + seconds
                                    }
                                    document.getElementById('hello').innerHTML = month + "/" + day + "/" + year + " " + hours + ":" + minutes + ":" + seconds + " ";
                                }

                                function Connect_disconnect() {
                                    if (document.getElementById('Dis_Connect').value == " Подключить ")
                                    {
                                        document.getElementById('TableResponse').innerHTML = user + '/' + collection + '/' + boardname;
                                        document.getElementById('Dis_Connect').value = "Отключить";
                                        //sendCommand('http://linux.mchpcloud.com/xml/' + user + '/' + collection + '/' + boardname + '/', updateStatusResponse, true);
                                        StopAJAX = 0;
                                        updateTime();
                                        newAJAXCommand(URL+'/xml/' + user + '/' + collection + '/' + boardname + '/', "GET" ,updateStatusResponse, true);
                                    } else
                                    {
                                        KillAjax();
                                        document.getElementById('footer').innerHTML = "Copyright &copy; 2013 Microchip Technology, Inc.";
                                        document.getElementById('footer').style.color = 'grey';
                                        Time = new Date();
                                        document.getElementById('Dis_Connect').value = " Подключить ";
                                    }
                                }
                                function toggleLED(value)
                                {
                                    var data;
                                    data ='<record><username>'+user+'</username><collection>'+collection+'</collection><board>'+boardname+'</board><ledtoggle>'+value+'</ledtoggle></record>';
                                    if (document.getElementById('Dis_Connect').value == "Отключить")  //if we are connected
                                    {
                                        StopAJAX = 0;
                                        updateTime();
                                        newAJAXCommand(URL+'/xml/' + user + '/' + collection + '/' + boardname +'/',"PUT",null,0,data);
                                    }
                                }    

                                function sendCommand(value, container, repeat, data)
                                {
                                    if (document.getElementById('Dis_Connect').value == "Отключить")  //if we are connected
                                    {
                                        StopAJAX = 0;
                                        updateTime();
                                        newAJAXCommand(value, "GET" ,container, repeat, data);
                                    }
                                }
                                function updateTime()
                                {
                                    AlreadyCalled = 0;
                                    document.getElementById('footer').innerHTML = "Copyright &copy; 2013 Microchip Technology, Inc.";
                                    document.getElementById('footer').style.color = 'grey';
                                    Time = new Date();
                                }
                                function logOut()
                                {
                                    var d = new Date();
                                    if ((d.getTime() - Time.getTime()) > 5000)
                                        Connect_disconnect(); 
                                }
                                var elapsed;
                                var timeOutMS = 1000; //ms
                                var timeOutSEC = 1000; //1000 mSec
                                var HeartBeat = 0;
                                var LastTimeChange = new Date().getTime();
                                var PotValue;

                                function updateStatusResponse(xmlData) {
                                    var mainstat = document.getElementById('display').style.display;
                                    var loadstat = document.getElementById('loading').style.display;
                                    var Response = new Array();
                                    var d = new Date();
                                    // Check if a timeout occurred
                                    if ((d.getTime() - Time.getTime()) > (timeOutSEC * 60 * 5))  // 5 minutes
                                    {
                                        //alert ("No activity for 60 seconds, you will be logged out");
                                        document.getElementById('footer').innerHTML = "Нет активности в течении 5 минут. Через 5 секунд Вы будете отключены";
                                        document.getElementById('footer').style.color = 'red';
                                        if (!AlreadyCalled)
                                        {
                                            setTimeout("logOut()", 5000);
                                            AlreadyCalled = 1;
                                        }
                                    }
                                    if (xmlData == null)
                                        return;
                                    Response = xmlData;
                                          // Check if a timeout occurred
                                    if (elapsed > timeOutMS)
                                    {
                                        mainstat = 'none';
                                        loadstat = 'inline';
                                        //return;
                                    }
                                    // Make sure we're displaying the status display
                                    mainstat = 'inline';
                                    loadstat = 'none';
                                    //document.write(Response);
                                    // Loop over all the LEDs
                                    var leds = getXMLValue(xmlData, 'leds');
                                    for (i = 0; i < 3; i++)
                                    {
                                        var test1 = Math.pow(2,i);
                                        var test = ((leds & (Math.pow(2,i))) == Math.pow(2,i));
                                        document.getElementById('led' + i).style.color = ((leds & (Math.pow(2,i))) == Math.pow(2,i)) ? '#090' : '#ddd';
                                    }
                                    // Loop over all the buttons
                                    var button = getXMLValue(xmlData, 'buttons' );
                                    i = 0;
//                                    for (i = 0; i < 4; i++)
//                                    {
                                       
                                        document.getElementById('btn0').innerHTML = ((button & (Math.pow(2,i))) == Math.pow(2,i)) ? '&Lambda;' : 'V';
//                                    }
                                    // Update the POT value
                                    var pot = getXMLValue(xmlData, 'pot');
                                    document.getElementById('pot0').innerHTML = getXMLValue(xmlData, 'pot');
//                                    var PortBarGraph = document.getElementById('PotBAR');
//                                    PortBarGraph.width = 178 * (document.getElementById('pot0').innerHTML / 1024);
                                    document.getElementById('TableResponse').innerHTML = "<?php echo $user."/".$collection."/".$board; ?>/<br> MAC:" + getXMLValue(xmlData, 'macaddr');
                                }

                                        document.getElementById('hello').innerHTML = "<?php echo "Добро пожаловать $login"; ?>";

                            </script>
                            <div class="spacer">&nbsp;</div>
                            <div class="spacer">&nbsp;</div><div id="footer">Copyright &copy; 2013 Microchip Technology, Inc.</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>
